package org.crepi22.finecrop;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 * @author pierre
 * A configuration panel for the application.
 */
public class ConfigPanel extends JFrame {

    private static final long serialVersionUID = 1L;
    JLabel labelConvertPath = new JLabel(Messages.getString("ConfigPanel.label_convert_path")); //$NON-NLS-1$
    JTextField editConvertPath = new JTextField(Config.getConvertPath(), 20);
    JButton confirmButton = new JButton(Messages.getString("ConfigPanel.confirm_button")); //$NON-NLS-1$
    
    /**
     * Set up the configuration panel. 
     */
    public ConfigPanel() {
        add(labelConvertPath);
        add(editConvertPath);
        add(confirmButton);
        confirmButton.addActionListener(new ActionListener() {            
            @Override
            public void actionPerformed(ActionEvent arg0) {
                updatePrefs();
            }
        });
        setLayout(new FlowLayout());
        setSize(200,200);
        setTitle(Messages.getString("ConfigPanel.settings_title")); //$NON-NLS-1$
        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        try {
            OS.decorate(this, null);
        } catch (IOException e) {
            // nothing
        }
    }

    /**
     * Change the configuration of options according to values.
     */
    protected void updatePrefs() {
        try {
            String newPath = editConvertPath.getText();
            if (! new File(newPath).isFile()) throw new IOException(String.format(Messages.getString("ConfigPanel.error_convert"),newPath)); //$NON-NLS-1$
            Config.setConvertPath(newPath);
            dispose();
        } catch (Exception e) {
            JOptionPane.showConfirmDialog(this, e.getMessage(), Messages.getString("ConfigPanel.error_title"), JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE); //$NON-NLS-1$
        }
    }
}
